import qs from "qs";
import cheerio from "cheerio";
import { URL, USERS } from "../../systems/cloud/config.js";
import { cloudAxios } from "../../systems/cloud/axios.js";
import RSAUtils from "./assistUtils/rsaUtils.js";
import { commonUtil } from "../index.js";

export async function cloudLogin() {
  if (global.cookie && global.unieap && global.hisConfigSession) {
    return { unieap: global.unieap, hisConfigSession: global.hisConfigSession };
  }
  const community = await commonUtil.selectCommunity(USERS);
  const user = USERS[community][0];

  const res = await cloudAxios({
    url: URL.LOGIN,
    params: {
      method: "begin",
    },
  });

  const preCookie = res.headers["set-cookie"][0].split(";")[0];
  const phisrandomflag = `phisrandomflag=${Math.random()}`;

  const res1 = await cloudAxios({
    url: URL.LOGIN,
    method: "post",
    params: {
      method: "begin",
    },
    headers: {
      Cookie: `${phisrandomflag}; ${preCookie}`,
      "Content-Type": "application/x-www-form-urlencoded",
    },
    data: qs.stringify({ t: new Date().getTime() }),
  });

  const { publicKeyExponent, publicKeyModulus } = res1.data;
  const j_password = base64Encrypt(
    publicKeyExponent,
    publicKeyModulus,
    user.password
  );

  const data = {
    ieversion: "",
    umsreceiveinstalled: "",
    j_username: user.username,
    j_password,
    publicKeyExponent,
    publicKeyModulus,
    macAddress: "",
    ipAddress: "",
    hostName: "",
  };

  const res2 = await cloudAxios({
    maxRedirects: 0,
    method: "post",
    url: URL.LOGIN_CHECK,
    headers: {
      "Content-Type": "application/x-www-form-urlencoded",
      Cookie: `${preCookie}; ${phisrandomflag}`,
    },
    params: {
      method: "begin",
    },
    data: qs.stringify(data),
  });

  const cookie = res2.headers["set-cookie"][0].split(";")[0];
  global.cookie = cookie;

  await cloudAxios({
    url: URL.LOGIN,
    params: {
      method: "login",
    },
  });

  const res6 = await cloudAxios({
    url: "/enterapp.do",
    params: {
      method: "begin",
      name: "/ph",
      welcome: "/ph/../public/menu/index.jsp",
      plugin: "yes",
    },
  });

  const res4 = await cloudAxios({
    url: "/ph/pages/welcome/welcome.jsp",
    params: {
      plugin: "yes",
    },
  });

  const $HTML4 = cheerio.load(res4.data);
  const window = { unieap: {} };
  const unieap = window.unieap;
  eval($HTML4("script").first().html());

  let hisConfigSession;
  $HTML4("script").each(function (index, el) {
    const $el = $HTML4(this);
    if ($el.html().includes("hisConfigSession")) {
      const gsPHRBrowserInfo = {};
      eval($el.html().replace(/var/g, ""));
    }
  });

  console.log(`登录成功，cookie：${cookie}`);
  global.hisConfigSession = hisConfigSession;
  global.unieap = unieap;
  return { hisConfigSession, unieap };
  // unieap = {
  //   phisCode: "1CA90827599FC849AF7DC9D3C95E57DD",
  //   WEB_APP_NAME: "/phis",
  //   appPath: "/phis/ph",
  //   appPath20: "",
  //   cmpPath: "/phis/ph/../public/menu/index.jsp",
  //   dialogRelogin: "true",
  //   isEncrypt: false,
  //   loginAccount: "ngpgh",
  //   orgId: "8abc4ab36699a6ce0166a064e6fb0031",
  //   orgCode: "440112505351",
  //   orgName: "广州市黄埔区南岗街社区卫生服务中心",
  //   stationId: "8abc4ab36699a6ce0166a064e6fb0031",
  //   stationCode: "440112505351",
  //   stationName: "广州市黄埔区南岗街社区卫生服务中心",
  //   deptId: "8a44a0967c267fc4017c6e2184400013",
  //   deptCode: "0007",
  //   deptName: "全科门诊",
  //   locale: "zh_CN",
  //   refererURL: "null",
  //   currentOrgLicense: "",
  //   excptionSep: "%##%",
  //   codeMessageSep: ": ",
  //   themes: "/phis/public/ria/themes/blue",
  //   systemInfo: {
  //     IPADDRESS: "10.196.32.23",
  //     HOSTNAME: "WIN-P7CQVSNUOVO",
  //     USERNAME: "administrator",
  //     COMPUTERNAME: "WIN-P7CQVSNUOVO",
  //     USERDOMAIN: "WIN-P7CQVSNUOVO",
  //     JvmMemoryTotal: "17056661504",
  //     JvmMemoryFree: "9837114240",
  //     JvmCpuCount: "8",
  //     OsName: "Windows Server 2012 R2",
  //     OsArch: "amd64",
  //     OsVersion: "6.3",
  //     OsLanguage: "zh",
  //     OsCountry: "CN",
  //     webAppRealPath: "D:\\apache-tomcat-7.0.100\\webapps\\phis\\",
  //     webServerInfo: "Apache Tomcat/7.0.109",
  //     webServerPort: "7001",
  //     webInputArgs:
  //       "[-Djava.util.logging.config.file=D:\\apache-tomcat-7.0.100\\conf\\logging.properties, -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager, -Xms16384M, -Xmx16384M, -XX:PermSize=1024M, -XX:MaxNewSize=5120M, -XX:MaxPermSize=1024M, -Dfile.encoding=UTF-8, -Djdk.tls.ephemeralDHKeySize=2048, -Dignore.endorsed.dirs=, -Dcatalina.base=D:\\apache-tomcat-7.0.100, -Dcatalina.home=D:\\apache-tomcat-7.0.100, -Djava.io.tmpdir=D:\\apache-tomcat-7.0.100\\temp]",
  //   },
  // };

  // hisConfigSession = {
  //   Sessionid: '2A4942AB1B0D4FE6B8EA0DEF6BED9923',
  //     UserId: '07823834AF2E426993A76DED73095F32',
  //   UserName: '潘广辉',
  //   UserCode: '015866',
  //   EmplType: '1',
  //   OrgId: '8abc4ab36699a6ce0166a064e6fb0031',
  //   OrgCode: '440112505351',
  //   OrgType: '3',
  //   HosGrade: '2',
  //   Chisunitcode: '440112008000',
  //   OrgName: '广州市黄埔区南岗街社区卫生服务中心',
  //   RecAuthority: '2',
  //   StationID: '8abc4ab36699a6ce0166a064e6fb0031',
  //   StationCode: '440112505351',
  //   StationName: '广州市黄埔区南岗街社区卫生服务中心',
  //   District: '',
  //   CurrentTimeLong: 1638363727411,
  //   DeptId: '8a44a0967c267fc4017c6e2184400013',
  //   DeptCode: '0007',
  //   DeptName: '全科门诊',
  //   DeptType: 'C',
  //   UserIDCardNo: '440111198209081255',
  //   UserMobileNum: '',
  //   UnitGroup: '',
  //   UserDeptId: '8a44a0967c267fc4017c6e2184400013',
  //   UserDeptCode: '0007',
  //   UserDeptName: '全科门诊',
  //   CALoginDetail: '',
  //   UserProvinceName: '广东省',
  //   UserProvinceCode: '440000',
  //   UserCityName: '广州市',
  //   UserCityCode: '440100',
  //   UserDistrictName: '黄埔区',
  //   UserDistrictCode: '440112',
  //   UserCenterCode: '440112008000',
  //   isAdmin: false,
  //   isSuperAdmin: false,
  //   UserDocposition: '2',
  //   canDoPhCHSS: '2',
  //   UnitName: '第一团队',
  //   FTPUserName: '',
  //   FTPUserPassword: '',
  //   FTPDBBasePath: '',
  //   UnitId20: '8abc4ab36699a6ce0166a064e6fb0031',
  //   UnitCode20: '440112008001',
  //   UnitName20: '广州市黄埔区南岗街社区卫生服务中心',
  //   UserUnitType20: '3',
  //   UserId20: '07823834AF2E426993A76DED73095F32',
  //   UserCode20: '440112008001',
  //   UserName20: '潘广辉',
  //   UserCenterCode20: '440112008000',
  //   UserCenterName20: '广州市黄埔区南岗街社区卫生服务中心',
  //   UserStationCode20: '440112008001',
  //   UserStationName20: '第一团队',
  //   TeamCode20: '440112008001',
  //   TeamName20: '第一团队',
  //   ManageMode20: '1',
  //   Identitycardno: '440111198209081255',
  //   MobileNum: '',
  //   CertifiedDocno: '110440104001861'
  // }
}

function base64Encrypt(publicKeyExponent, publicKeyModulus, password) {
  RSAUtils.setMaxDigits(200);
  const key = new RSAUtils.getKeyPair(publicKeyExponent, "", publicKeyModulus);
  return RSAUtils.encryptedString(key, password);
}
